home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / awksrc.zip / GAWK-D~1.14 / GAWK~2.INF (.txt) < prev    next >
GNU Info File  |  1993-10-03  |  48KB  |  836 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.47 from the input
  2. file gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.14 of `The GAWK Manual',
  6. for the 2.14 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Top,  Next: Preface,  Prev: (dir),  Up: (dir)
  21. General Introduction
  22. ********************
  23.    This file documents `awk', a program that you can use to select
  24. particular records in a file and perform operations upon them.
  25.    This is Edition 0.14 of `The GAWK Manual',
  26. for the 2.14 version of the GNU implementation
  27. of AWK.
  28. * Menu:
  29. * Preface::                     What you can do with `awk'; brief history
  30.                                 and acknowledgements.
  31. * Copying::                     Your right to copy and distribute `gawk'.
  32. * This Manual::                 Using this manual.
  33.                                 Includes sample input files that you can use.
  34. * Getting Started::             A basic introduction to using `awk'.
  35.                                 How to run an `awk' program.
  36.                                 Command line syntax.
  37. * Reading Files::               How to read files and manipulate fields.
  38. * Printing::                    How to print using `awk'.  Describes the
  39.                                 `print' and `printf' statements.
  40.                                 Also describes redirection of output.
  41. * One-liners::                  Short, sample `awk' programs.
  42. * Patterns::                    The various types of patterns
  43.                                 explained in detail.
  44. * Actions::                     The various types of actions are
  45.                                 introduced here.  Describes
  46.                                 expressions and the various operators in
  47.                                 detail.  Also describes comparison expressions.
  48. * Expressions::                 Expressions are the basic building
  49.                                 blocks of statements.
  50. * Statements::                  The various control statements are
  51.                                 described in detail.
  52. * Arrays::                      The description and use of arrays.
  53.                                 Also includes array-oriented control
  54.                                 statements.
  55. * Built-in::                    The built-in functions are summarized here.
  56. * User-defined::                User-defined functions are described in detail.
  57. * Built-in Variables::          Built-in Variables
  58. * Command Line::                How to run `gawk'.
  59. * Language History::            The evolution of the `awk' language.
  60. * Installation::                Installing `gawk' under
  61.                                 various operating systems.
  62. * Gawk Summary::                `gawk' Options and Language Summary.
  63. * Sample Program::              A sample `awk' program with a
  64.                                 complete explanation.
  65. * Bugs::                        Reporting Problems and Bugs.
  66. * Notes::                       Something about the
  67.                                 implementation of `gawk'.
  68. * Glossary::                    An explanation of some unfamiliar terms.
  69. * Index::
  70. File: gawk.info,  Node: Preface,  Next: Copying,  Prev: Top,  Up: Top
  71. Preface
  72. *******
  73.    If you are like many computer users, you would frequently like to
  74. make changes in various text files wherever certain patterns appear, or
  75. extract data from parts of certain lines while discarding the rest.  To
  76. write a program to do this in a language such as C or Pascal is a
  77. time-consuming inconvenience that may take many lines of code.  The job
  78. may be easier with `awk'.
  79.    The `awk' utility interprets a special-purpose programming language
  80. that makes it possible to handle simple data-reformatting jobs easily
  81. with just a few lines of code.
  82.    The GNU implementation of `awk' is called `gawk'; it is fully upward
  83. compatible with the System V Release 4 version of `awk'.  `gawk' is
  84. also upward compatible with the POSIX (draft) specification of the
  85. `awk' language.  This means that all properly written `awk' programs
  86. should work with `gawk'. Thus, we usually don't distinguish between
  87. `gawk' and other `awk' implementations in this manual.
  88.    This manual teaches you what `awk' does and how you can use `awk'
  89. effectively.  You should already be familiar with basic system commands
  90. such as `ls'.  Using `awk' you can:
  91.    * manage small, personal databases
  92.    * generate reports
  93.    * validate data
  94.    * produce indexes, and perform other document preparation tasks
  95.    * even experiment with algorithms that can be adapted later to other
  96.      computer languages
  97. * Menu:
  98. * History::                     The history of `gawk' and
  99.                                 `awk'.  Acknowledgements.
  100. File: gawk.info,  Node: History,  Prev: Preface,  Up: Preface
  101. History of `awk' and `gawk'
  102. ===========================
  103.    The name `awk' comes from the initials of its designers: Alfred V.
  104. Aho, Peter J. Weinberger, and Brian W. Kernighan.  The original version
  105. of `awk' was written in 1977.  In 1985 a new version made the
  106. programming language more powerful, introducing user-defined functions,
  107. multiple input streams, and computed regular expressions. This new
  108. version became generally available with System V Release 3.1. The
  109. version in System V Release 4 added some new features and also cleaned
  110. up the behavior in some of the "dark corners" of the language. The
  111. specification for `awk' in the POSIX Command Language and Utilities
  112. standard further clarified the language based on feedback from both the
  113. `gawk' designers, and the original `awk' designers.
  114.    The GNU implementation, `gawk', was written in 1986 by Paul Rubin
  115. and Jay Fenlason, with advice from Richard Stallman.  John Woods
  116. contributed parts of the code as well.  In 1988 and 1989, David
  117. Trueman, with help from Arnold Robbins, thoroughly reworked `gawk' for
  118. compatibility with the newer `awk'.  Current development (1992) focuses
  119. on bug fixes, performance improvements, and standards compliance.
  120.    We need to thank many people for their assistance in producing this
  121. manual.  Jay Fenlason contributed many ideas and sample programs. 
  122. Richard Mlynarik and Robert J. Chassell gave helpful comments on early
  123. drafts of this manual.  The paper `A Supplemental Document for `awk''
  124. by John W. Pierce of the Chemistry Department at UC San Diego,
  125. pinpointed several issues relevant both to `awk' implementation and to
  126. this manual, that would otherwise have escaped us.  David Trueman, Pat
  127. Rankin, and Michal Jaegermann also contributed sections of the manual.
  128.    The following people provided many helpful comments on this edition
  129. of the manual: Rick Adams, Michael Brennan, Rich Burridge, Diane Close,
  130. Christopher ("Topher") Eliot, Michael Lijewski, Pat Rankin, Miriam
  131. Robbins, and Michal Jaegermann.  Robert J. Chassell provided much
  132. valuable advice on the use of Texinfo.
  133.    Finally, we would like to thank Brian Kernighan of Bell Labs for
  134. invaluable assistance during the testing and debugging of `gawk', and
  135. for help in clarifying numerous points about the language.
  136. File: gawk.info,  Node: Copying,  Next: This Manual,  Prev: Preface,  Up: Top
  137. GNU GENERAL PUBLIC LICENSE
  138. **************************
  139.                          Version 2, June 1991
  140.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  141.      675 Mass Ave, Cambridge, MA 02139, USA
  142.      
  143.      Everyone is permitted to copy and distribute verbatim copies
  144.      of this license document, but changing it is not allowed.
  145. Preamble
  146. ========
  147.    The licenses for most software are designed to take away your
  148. freedom to share and change it.  By contrast, the GNU General Public
  149. License is intended to guarantee your freedom to share and change free
  150. software--to make sure the software is free for all its users.  This
  151. General Public License applies to most of the Free Software
  152. Foundation's software and to any other program whose authors commit to
  153. using it.  (Some other Free Software Foundation software is covered by
  154. the GNU Library General Public License instead.)  You can apply it to
  155. your programs, too.
  156.    When we speak of free software, we are referring to freedom, not
  157. price.  Our General Public Licenses are designed to make sure that you
  158. have the freedom to distribute copies of free software (and charge for
  159. this service if you wish), that you receive source code or can get it
  160. if you want it, that you can change the software or use pieces of it in
  161. new free programs; and that you know you can do these things.
  162.    To protect your rights, we need to make restrictions that forbid
  163. anyone to deny you these rights or to ask you to surrender the rights.
  164. These restrictions translate to certain responsibilities for you if you
  165. distribute copies of the software, or if you modify it.
  166.    For example, if you distribute copies of such a program, whether
  167. gratis or for a fee, you must give the recipients all the rights that
  168. you have.  You must make sure that they, too, receive or can get the
  169. source code.  And you must show them these terms so they know their
  170. rights.
  171.    We protect your rights with two steps: (1) copyright the software,
  172. and (2) offer you this license which gives you legal permission to copy,
  173. distribute and/or modify the software.
  174.    Also, for each author's protection and ours, we want to make certain
  175. that everyone understands that there is no warranty for this free
  176. software.  If the software is modified by someone else and passed on, we
  177. want its recipients to know that what they have is not the original, so
  178. that any problems introduced by others will not reflect on the original
  179. authors' reputations.
  180.    Finally, any free program is threatened constantly by software
  181. patents.  We wish to avoid the danger that redistributors of a free
  182. program will individually obtain patent licenses, in effect making the
  183. program proprietary.  To prevent this, we have made it clear that any
  184. patent must be licensed for everyone's free use or not licensed at all.
  185.    The precise terms and conditions for copying, distribution and
  186. modification follow.
  187.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  188.   1. This License applies to any program or other work which contains a
  189.      notice placed by the copyright holder saying it may be distributed
  190.      under the terms of this General Public License.  The "Program",
  191.      below, refers to any such program or work, and a "work based on
  192.      the Program" means either the Program or any derivative work under
  193.      copyright law: that is to say, a work containing the Program or a
  194.      portion of it, either verbatim or with modifications and/or
  195.      translated into another language.  (Hereinafter, translation is
  196.      included without limitation in the term "modification".)  Each
  197.      licensee is addressed as "you".
  198.      Activities other than copying, distribution and modification are
  199.      not covered by this License; they are outside its scope.  The act
  200.      of running the Program is not restricted, and the output from the
  201.      Program is covered only if its contents constitute a work based on
  202.      the Program (independent of having been made by running the
  203.      Program). Whether that is true depends on what the Program does.
  204.   2. You may copy and distribute verbatim copies of the Program's
  205.      source code as you receive it, in any medium, provided that you
  206.      conspicuously and appropriately publish on each copy an appropriate
  207.      copyright notice and disclaimer of warranty; keep intact all the
  208.      notices that refer to this License and to the absence of any
  209.      warranty; and give any other recipients of the Program a copy of
  210.      this License along with the Program.
  211.      You may charge a fee for the physical act of transferring a copy,
  212.      and you may at your option offer warranty protection in exchange
  213.      for a fee.
  214.   3. You may modify your copy or copies of the Program or any portion
  215.      of it, thus forming a work based on the Program, and copy and
  216.      distribute such modifications or work under the terms of Section 1
  217.      above, provided that you also meet all of these conditions:
  218.        a. You must cause the modified files to carry prominent notices
  219.           stating that you changed the files and the date of any change.
  220.        b. You must cause any work that you distribute or publish, that
  221.           in whole or in part contains or is derived from the Program
  222.           or any part thereof, to be licensed as a whole at no charge
  223.           to all third parties under the terms of this License.
  224.        c. If the modified program normally reads commands interactively
  225.           when run, you must cause it, when started running for such
  226.           interactive use in the most ordinary way, to print or display
  227.           an announcement including an appropriate copyright notice and
  228.           a notice that there is no warranty (or else, saying that you
  229.           provide a warranty) and that users may redistribute the
  230.           program under these conditions, and telling the user how to
  231.           view a copy of this License.  (Exception: if the Program
  232.           itself is interactive but does not normally print such an
  233.           announcement, your work based on the Program is not required
  234.           to print an announcement.)
  235.      These requirements apply to the modified work as a whole.  If
  236.      identifiable sections of that work are not derived from the
  237.      Program, and can be reasonably considered independent and separate
  238.      works in themselves, then this License, and its terms, do not
  239.      apply to those sections when you distribute them as separate
  240.      works.  But when you distribute the same sections as part of a
  241.      whole which is a work based on the Program, the distribution of
  242.      the whole must be on the terms of this License, whose permissions
  243.      for other licensees extend to the entire whole, and thus to each
  244.      and every part regardless of who wrote it.
  245.      Thus, it is not the intent of this section to claim rights or
  246.      contest your rights to work written entirely by you; rather, the
  247.      intent is to exercise the right to control the distribution of
  248.      derivative or collective works based on the Program.
  249.      In addition, mere aggregation of another work not based on the
  250.      Program with the Program (or with a work based on the Program) on
  251.      a volume of a storage or distribution medium does not bring the
  252.      other work under the scope of this License.
  253.   4. You may copy and distribute the Program (or a work based on it,
  254.      under Section 2) in object code or executable form under the terms
  255.      of Sections 1 and 2 above provided that you also do one of the
  256.      following:
  257.        a. Accompany it with the complete corresponding machine-readable
  258.           source code, which must be distributed under the terms of
  259.           Sections 1 and 2 above on a medium customarily used for
  260.           software interchange; or,
  261.        b. Accompany it with a written offer, valid for at least three
  262.           years, to give any third party, for a charge no more than your
  263.           cost of physically performing source distribution, a complete
  264.           machine-readable copy of the corresponding source code, to be
  265.           distributed under the terms of Sections 1 and 2 above on a
  266.           medium customarily used for software interchange; or,
  267.        c. Accompany it with the information you received as to the offer
  268.           to distribute corresponding source code.  (This alternative is
  269.           allowed only for noncommercial distribution and only if you
  270.           received the program in object code or executable form with
  271.           such an offer, in accord with Subsection b above.)
  272.      The source code for a work means the preferred form of the work for
  273.      making modifications to it.  For an executable work, complete
  274.      source code means all the source code for all modules it contains,
  275.      plus any associated interface definition files, plus the scripts
  276.      used to control compilation and installation of the executable. 
  277.      However, as a special exception, the source code distributed need
  278.      not include anything that is normally distributed (in either
  279.      source or binary form) with the major components (compiler,
  280.      kernel, and so on) of the operating system on which the executable
  281.      runs, unless that component itself accompanies the executable.
  282.      If distribution of executable or object code is made by offering
  283.      access to copy from a designated place, then offering equivalent
  284.      access to copy the source code from the same place counts as
  285.      distribution of the source code, even though third parties are not
  286.      compelled to copy the source along with the object code.
  287.   5. You may not copy, modify, sublicense, or distribute the Program
  288.      except as expressly provided under this License.  Any attempt
  289.      otherwise to copy, modify, sublicense or distribute the Program is
  290.      void, and will automatically terminate your rights under this
  291.      License. However, parties who have received copies, or rights,
  292.      from you under this License will not have their licenses
  293.      terminated so long as such parties remain in full compliance.
  294.   6. You are not required to accept this License, since you have not
  295.      signed it.  However, nothing else grants you permission to modify
  296.      or distribute the Program or its derivative works.  These actions
  297.      are prohibited by law if you do not accept this License. 
  298.      Therefore, by modifying or distributing the Program (or any work
  299.      based on the Program), you indicate your acceptance of this
  300.      License to do so, and all its terms and conditions for copying,
  301.      distributing or modifying the Program or works based on it.
  302.   7. Each time you redistribute the Program (or any work based on the
  303.      Program), the recipient automatically receives a license from the
  304.      original licensor to copy, distribute or modify the Program
  305.      subject to these terms and conditions.  You may not impose any
  306.      further restrictions on the recipients' exercise of the rights
  307.      granted herein. You are not responsible for enforcing compliance
  308.      by third parties to this License.
  309.   8. If, as a consequence of a court judgment or allegation of patent
  310.      infringement or for any other reason (not limited to patent
  311.      issues), conditions are imposed on you (whether by court order,
  312.      agreement or otherwise) that contradict the conditions of this
  313.      License, they do not excuse you from the conditions of this
  314.      License.  If you cannot distribute so as to satisfy simultaneously
  315.      your obligations under this License and any other pertinent
  316.      obligations, then as a consequence you may not distribute the
  317.      Program at all.  For example, if a patent license would not permit
  318.      royalty-free redistribution of the Program by all those who
  319.      receive copies directly or indirectly through you, then the only
  320.      way you could satisfy both it and this License would be to refrain
  321.      entirely from distribution of the Program.
  322.      If any portion of this section is held invalid or unenforceable
  323.      under any particular circumstance, the balance of the section is
  324.      intended to apply and the section as a whole is intended to apply
  325.      in other circumstances.
  326.      It is not the purpose of this section to induce you to infringe any
  327.      patents or other property right claims or to contest validity of
  328.      any such claims; this section has the sole purpose of protecting
  329.      the integrity of the free software distribution system, which is
  330.      implemented by public license practices.  Many people have made
  331.      generous contributions to the wide range of software distributed
  332.      through that system in reliance on consistent application of that
  333.      system; it is up to the author/donor to decide if he or she is
  334.      willing to distribute software through any other system and a
  335.      licensee cannot impose that choice.
  336.      This section is intended to make thoroughly clear what is believed
  337.      to be a consequence of the rest of this License.
  338.   9. If the distribution and/or use of the Program is restricted in
  339.      certain countries either by patents or by copyrighted interfaces,
  340.      the original copyright holder who places the Program under this
  341.      License may add an explicit geographical distribution limitation
  342.      excluding those countries, so that distribution is permitted only
  343.      in or among countries not thus excluded.  In such case, this
  344.      License incorporates the limitation as if written in the body of
  345.      this License.
  346.  10. The Free Software Foundation may publish revised and/or new
  347.      versions of the General Public License from time to time.  Such
  348.      new versions will be similar in spirit to the present version, but
  349.      may differ in detail to address new problems or concerns.
  350.      Each version is given a distinguishing version number.  If the
  351.      Program specifies a version number of this License which applies
  352.      to it and "any later version", you have the option of following
  353.      the terms and conditions either of that version or of any later
  354.      version published by the Free Software Foundation.  If the Program
  355.      does not specify a version number of this License, you may choose
  356.      any version ever published by the Free Software Foundation.
  357.  11. If you wish to incorporate parts of the Program into other free
  358.      programs whose distribution conditions are different, write to the
  359.      author to ask for permission.  For software which is copyrighted
  360.      by the Free Software Foundation, write to the Free Software
  361.      Foundation; we sometimes make exceptions for this.  Our decision
  362.      will be guided by the two goals of preserving the free status of
  363.      all derivatives of our free software and of promoting the sharing
  364.      and reuse of software generally.
  365.                                 NO WARRANTY
  366.  12. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  367.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  368.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  369.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  370.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  371.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  372.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  373.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  374.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  375.      SERVICING, REPAIR OR CORRECTION.
  376.  13. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  377.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  378.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  379.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  380.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  381.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  382.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  383.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  384.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  385.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  386.                       END OF TERMS AND CONDITIONS
  387. How to Apply These Terms to Your New Programs
  388. =============================================
  389.    If you develop a new program, and you want it to be of the greatest
  390. possible use to the public, the best way to achieve this is to make it
  391. free software which everyone can redistribute and change under these
  392. terms.
  393.    To do so, attach the following notices to the program.  It is safest
  394. to attach them to the start of each source file to most effectively
  395. convey the exclusion of warranty; and each file should have at least
  396. the "copyright" line and a pointer to where the full notice is found.
  397.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  398.      Copyright (C) 19YY  NAME OF AUTHOR
  399.      
  400.      This program is free software; you can redistribute it and/or modify
  401.      it under the terms of the GNU General Public License as published by
  402.      the Free Software Foundation; either version 2 of the License, or
  403.      (at your option) any later version.
  404.      
  405.      This program is distributed in the hope that it will be useful,
  406.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  407.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  408.      GNU General Public License for more details.
  409.      
  410.      You should have received a copy of the GNU General Public License
  411.      along with this program; if not, write to the Free Software
  412.      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  413.    Also add information on how to contact you by electronic and paper
  414. mail.
  415.    If the program is interactive, make it output a short notice like
  416. this when it starts in an interactive mode:
  417.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  418.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  419.      This is free software, and you are welcome to redistribute it
  420.      under certain conditions; type `show c' for details.
  421.    The hypothetical commands `show w' and `show c' should show the
  422. appropriate parts of the General Public License.  Of course, the
  423. commands you use may be called something other than `show w' and `show
  424. c'; they could even be mouse-clicks or menu items--whatever suits your
  425. program.
  426.    You should also get your employer (if you work as a programmer) or
  427. your school, if any, to sign a "copyright disclaimer" for the program,
  428. if necessary.  Here is a sample; alter the names:
  429.      Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  430.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  431.      
  432.      SIGNATURE OF TY COON, 1 April 1989
  433.      Ty Coon, President of Vice
  434.    This General Public License does not permit incorporating your
  435. program into proprietary programs.  If your program is a subroutine
  436. library, you may consider it more useful to permit linking proprietary
  437. applications with the library.  If this is what you want to do, use the
  438. GNU Library General Public License instead of this License.
  439. File: gawk.info,  Node: This Manual,  Next: Getting Started,  Prev: Copying,  Up: Top
  440. Using this Manual
  441. *****************
  442.    The term `awk' refers to a particular program, and to the language
  443. you use to tell this program what to do.  When we need to be careful,
  444. we call the program "the `awk' utility" and the language "the `awk'
  445. language."  The term `gawk' refers to a version of `awk' developed as
  446. part the GNU project.  The purpose of this manual is to explain both the
  447. `awk' language and how to run the `awk' utility.
  448.    While concentrating on the features of `gawk', the manual will also
  449. attempt to describe important differences between `gawk' and other
  450. `awk' implementations.  In particular, any features that are not in the
  451. POSIX standard for `awk' will be noted.
  452.    The term "`awk' program" refers to a program written by you in the
  453. `awk' programming language.
  454.    *Note Getting Started with `awk': Getting Started, for the bare
  455. essentials you need to know to start using `awk'.
  456.    Some useful "one-liners" are included to give you a feel for the
  457. `awk' language (*note Useful "One-liners": One-liners.).
  458.    A sample `awk' program has been provided for you (*note Sample
  459. Program::.).
  460.    If you find terms that you aren't familiar with, try looking them up
  461. in the glossary (*note Glossary::.).
  462.    The entire `awk' language is summarized for quick reference in *Note
  463. `gawk' Summary: Gawk Summary.  Look there if you just need to refresh
  464. your memory about a particular feature.
  465.    Most of the time complete `awk' programs are used as examples, but in
  466. some of the more advanced sections, only the part of the `awk' program
  467. that illustrates the concept being described is shown.
  468. * Menu:
  469. * Sample Data Files::           Sample data files for use in the `awk'
  470.                                 programs illustrated in this manual.
  471. File: gawk.info,  Node: Sample Data Files,  Prev: This Manual,  Up: This Manual
  472. Data Files for the Examples
  473. ===========================
  474.    Many of the examples in this manual take their input from two sample
  475. data files.  The first, called `BBS-list', represents a list of
  476. computer bulletin board systems together with information about those
  477. systems. The second data file, called `inventory-shipped', contains
  478. information about shipments on a monthly basis.  Each line of these
  479. files is one "record".
  480.    In the file `BBS-list', each record contains the name of a computer
  481. bulletin board, its phone number, the board's baud rate, and a code for
  482. the number of hours it is operational.  An `A' in the last column means
  483. the board operates 24 hours a day.  A `B' in the last column means the
  484. board operates evening and weekend hours, only.  A `C' means the board
  485. operates only on weekends.
  486.      aardvark     555-5553     1200/300          B
  487.      alpo-net     555-3412     2400/1200/300     A
  488.      barfly       555-7685     1200/300          A
  489.      bites        555-1675     2400/1200/300     A
  490.      camelot      555-0542     300               C
  491.      core         555-2912     1200/300          C
  492.      fooey        555-1234     2400/1200/300     B
  493.      foot         555-6699     1200/300          B
  494.      macfoo       555-6480     1200/300          A
  495.      sdace        555-3430     2400/1200/300     A
  496.      sabafoo      555-2127     1200/300          C
  497.    The second data file, called `inventory-shipped', represents
  498. information about shipments during the year. Each record contains the
  499. month of the year, the number of green crates shipped, the number of
  500. red boxes shipped, the number of orange bags shipped, and the number of
  501. blue packages shipped, respectively.  There are 16 entries, covering
  502. the 12 months of one year and 4 months of the next year.
  503.      Jan  13  25  15 115
  504.      Feb  15  32  24 226
  505.      Mar  15  24  34 228
  506.      Apr  31  52  63 420
  507.      May  16  34  29 208
  508.      Jun  31  42  75 492
  509.      Jul  24  34  67 436
  510.      Aug  15  34  47 316
  511.      Sep  13  55  37 277
  512.      Oct  29  54  68 525
  513.      Nov  20  87  82 577
  514.      Dec  17  35  61 401
  515.      
  516.      Jan  21  36  64 620
  517.      Feb  26  58  80 652
  518.      Mar  24  75  70 495
  519.      Apr  21  70  74 514
  520.    If you are reading this in GNU Emacs using Info, you can copy the
  521. regions of text showing these sample files into your own test files. 
  522. This way you can try out the examples shown in the remainder of this
  523. document.  You do this by using the command `M-x write-region' to copy
  524. text from the Info file into a file for use with `awk' (*Note Misc File
  525. Ops: (emacs)Misc File Ops, for more information).  Using this
  526. information, create your own `BBS-list' and `inventory-shipped' files,
  527. and practice what you learn in this manual.
  528. File: gawk.info,  Node: Getting Started,  Next: Reading Files,  Prev: This Manual,  Up: Top
  529. Getting Started with `awk'
  530. **************************
  531.    The basic function of `awk' is to search files for lines (or other
  532. units of text) that contain certain patterns.  When a line matches one
  533. of the patterns, `awk' performs specified actions on that line. `awk'
  534. keeps processing input lines in this way until the end of the input
  535. file is reached.
  536.    When you run `awk', you specify an `awk' "program" which tells `awk'
  537. what to do.  The program consists of a series of "rules".  (It may also
  538. contain "function definitions", but that is an advanced feature, so we
  539. will ignore it for now. *Note User-defined Functions: User-defined.) 
  540. Each rule specifies one pattern to search for, and one action to
  541. perform when that pattern is found.
  542.    Syntactically, a rule consists of a pattern followed by an action. 
  543. The action is enclosed in curly braces to separate it from the pattern.
  544. Rules are usually separated by newlines.  Therefore, an `awk' program
  545. looks like this:
  546.      PATTERN { ACTION }
  547.      PATTERN { ACTION }
  548.      ...
  549. * Menu:
  550. * Very Simple::                 A very simple example.
  551. * Two Rules::                   A less simple one-line example with two rules.
  552. * More Complex::                A more complex example.
  553. * Running gawk::                How to run `gawk' programs;
  554.                                 includes command line syntax.
  555. * Comments::                    Adding documentation to `gawk' programs.
  556. * Statements/Lines::            Subdividing or combining statements into lines.
  557. * When::                        When to use `gawk' and
  558.                                 when to use other things.
  559. File: gawk.info,  Node: Very Simple,  Next: Two Rules,  Prev: Getting Started,  Up: Getting Started
  560. A Very Simple Example
  561. =====================
  562.    The following command runs a simple `awk' program that searches the
  563. input file `BBS-list' for the string of characters: `foo'.  (A string
  564. of characters is usually called, a "string". The term "string" is
  565. perhaps based on similar usage in English, such as "a string of
  566. pearls," or, "a string of cars in a train.")
  567.      awk '/foo/ { print $0 }' BBS-list
  568. When lines containing `foo' are found, they are printed, because
  569. `print $0' means print the current line.  (Just `print' by itself means
  570. the same thing, so we could have written that instead.)
  571.    You will notice that slashes, `/', surround the string `foo' in the
  572. actual `awk' program.  The slashes indicate that `foo' is a pattern to
  573. search for.  This type of pattern is called a "regular expression", and
  574. is covered in more detail later (*note Regular Expressions as Patterns:
  575. Regexp.).  There are single-quotes around the `awk' program so that the
  576. shell won't interpret any of it as special shell characters.
  577.    Here is what this program prints:
  578.      fooey        555-1234     2400/1200/300     B
  579.      foot         555-6699     1200/300          B
  580.      macfoo       555-6480     1200/300          A
  581.      sabafoo      555-2127     1200/300          C
  582.    In an `awk' rule, either the pattern or the action can be omitted,
  583. but not both.  If the pattern is omitted, then the action is performed
  584. for *every* input line.  If the action is omitted, the default action
  585. is to print all lines that match the pattern.
  586.    Thus, we could leave out the action (the `print' statement and the
  587. curly braces) in the above example, and the result would be the same:
  588. all lines matching the pattern `foo' would be printed.  By comparison,
  589. omitting the `print' statement but retaining the curly braces makes an
  590. empty action that does nothing; then no lines would be printed.
  591. File: gawk.info,  Node: Two Rules,  Next: More Complex,  Prev: Very Simple,  Up: Getting Started
  592. An Example with Two Rules
  593. =========================
  594.    The `awk' utility reads the input files one line at a time.  For
  595. each line, `awk' tries the patterns of each of the rules. If several
  596. patterns match then several actions are run, in the order in which they
  597. appear in the `awk' program.  If no patterns match, then no actions are
  598.    After processing all the rules (perhaps none) that match the line,
  599. `awk' reads the next line (however, *note The `next' Statement: Next
  600. Statement.).  This continues until the end of the file is reached.
  601.    For example, the `awk' program:
  602.      /12/  { print $0 }
  603.      /21/  { print $0 }
  604. contains two rules.  The first rule has the string `12' as the pattern
  605. and `print $0' as the action.  The second rule has the string `21' as
  606. the pattern and also has `print $0' as the action.  Each rule's action
  607. is enclosed in its own pair of braces.
  608.    This `awk' program prints every line that contains the string `12'
  609. *or* the string `21'.  If a line contains both strings, it is printed
  610. twice, once by each rule.
  611.    If we run this program on our two sample data files, `BBS-list' and
  612. `inventory-shipped', as shown here:
  613.      awk '/12/ { print $0 }
  614.           /21/ { print $0 }' BBS-list inventory-shipped
  615. we get the following output:
  616.      aardvark     555-5553     1200/300          B
  617.      alpo-net     555-3412     2400/1200/300     A
  618.      barfly       555-7685     1200/300          A
  619.      bites        555-1675     2400/1200/300     A
  620.      core         555-2912     1200/300          C
  621.      fooey        555-1234     2400/1200/300     B
  622.      foot         555-6699     1200/300          B
  623.      macfoo       555-6480     1200/300          A
  624.      sdace        555-3430     2400/1200/300     A
  625.      sabafoo      555-2127     1200/300          C
  626.      sabafoo      555-2127     1200/300          C
  627.      Jan  21  36  64 620
  628.      Apr  21  70  74 514
  629. Note how the line in `BBS-list' beginning with `sabafoo' was printed
  630. twice, once for each rule.
  631. File: gawk.info,  Node: More Complex,  Next: Running gawk,  Prev: Two Rules,  Up: Getting Started
  632. A More Complex Example
  633. ======================
  634.    Here is an example to give you an idea of what typical `awk'
  635. programs do.  This example shows how `awk' can be used to summarize,
  636. select, and rearrange the output of another utility.  It uses features
  637. that haven't been covered yet, so don't worry if you don't understand
  638. all the details.
  639.      ls -l | awk '$5 == "Nov" { sum += $4 }
  640.                   END { print sum }'
  641.    This command prints the total number of bytes in all the files in the
  642. current directory that were last modified in November (of any year).
  643. (In the C shell you would need to type a semicolon and then a backslash
  644. at the end of the first line; in a POSIX-compliant shell, such as the
  645. Bourne shell or the Bourne-Again shell, you can type the example as
  646. shown.)
  647.    The `ls -l' part of this example is a command that gives you a
  648. listing of the files in a directory, including file size and date. Its
  649. output looks like this:
  650.      -rw-r--r--  1 close        1933 Nov  7 13:05 Makefile
  651.      -rw-r--r--  1 close       10809 Nov  7 13:03 gawk.h
  652.      -rw-r--r--  1 close         983 Apr 13 12:14 gawk.tab.h
  653.      -rw-r--r--  1 close       31869 Jun 15 12:20 gawk.y
  654.      -rw-r--r--  1 close       22414 Nov  7 13:03 gawk1.c
  655.      -rw-r--r--  1 close       37455 Nov  7 13:03 gawk2.c
  656.      -rw-r--r--  1 close       27511 Dec  9 13:07 gawk3.c
  657.      -rw-r--r--  1 close        7989 Nov  7 13:03 gawk4.c
  658. The first field contains read-write permissions, the second field
  659. contains the number of links to the file, and the third field
  660. identifies the owner of the file.  The fourth field contains the size
  661. of the file in bytes.  The fifth, sixth, and seventh fields contain the
  662. month, day, and time, respectively, that the file was last modified. 
  663. Finally, the eighth field contains the name of the file.
  664.    The `$5 == "Nov"' in our `awk' program is an expression that tests
  665. whether the fifth field of the output from `ls -l' matches the string
  666. `Nov'.  Each time a line has the string `Nov' in its fifth field, the
  667. action `{ sum += $4 }' is performed.  This adds the fourth field (the
  668. file size) to the variable `sum'.  As a result, when `awk' has finished
  669. reading all the input lines, `sum' is the sum of the sizes of files
  670. whose lines matched the pattern.  (This works because `awk' variables
  671. are automatically initialized to zero.)
  672.    After the last line of output from `ls' has been processed, the
  673. `END' rule is executed, and the value of `sum' is printed.  In this
  674. example, the value of `sum' would be 80600.
  675.    These more advanced `awk' techniques are covered in later sections
  676. (*note Overview of Actions: Actions.).  Before you can move on to more
  677. advanced `awk' programming, you have to know how `awk' interprets your
  678. input and displays your output.  By manipulating fields and using
  679. `print' statements, you can produce some very useful and spectacular
  680. looking reports.
  681. File: gawk.info,  Node: Running gawk,  Next: Comments,  Prev: More Complex,  Up: Getting Started
  682. How to Run `awk' Programs
  683. =========================
  684.    There are several ways to run an `awk' program.  If the program is
  685. short, it is easiest to include it in the command that runs `awk', like
  686. this:
  687.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  688. where PROGRAM consists of a series of patterns and actions, as
  689. described earlier.
  690.    When the program is long, it is usually more convenient to put it in
  691. a file and run it with a command like this:
  692.      awk -f PROGRAM-FILE INPUT-FILE1 INPUT-FILE2 ...
  693. * Menu:
  694. * One-shot::                    Running a short throw-away `awk' program.
  695. * Read Terminal::               Using no input files (input from
  696.                                 terminal instead).
  697. * Long::                        Putting permanent `awk' programs in files.
  698. * Executable Scripts::          Making self-contained `awk' programs.
  699. File: gawk.info,  Node: One-shot,  Next: Read Terminal,  Prev: Running gawk,  Up: Running gawk
  700. One-shot Throw-away `awk' Programs
  701. ----------------------------------
  702.    Once you are familiar with `awk', you will often type simple
  703. programs at the moment you want to use them.  Then you can write the
  704. program as the first argument of the `awk' command, like this:
  705.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  706. where PROGRAM consists of a series of PATTERNS and ACTIONS, as
  707. described earlier.
  708.    This command format instructs the shell to start `awk' and use the
  709. PROGRAM to process records in the input file(s).  There are single
  710. quotes around PROGRAM so that the shell doesn't interpret any `awk'
  711. characters as special shell characters.  They also cause the shell to
  712. treat all of PROGRAM as a single argument for `awk' and allow PROGRAM
  713. to be more than one line long.
  714.    This format is also useful for running short or medium-sized `awk'
  715. programs from shell scripts, because it avoids the need for a separate
  716. file for the `awk' program.  A self-contained shell script is more
  717. reliable since there are no other files to misplace.
  718. File: gawk.info,  Node: Read Terminal,  Next: Long,  Prev: One-shot,  Up: Running gawk
  719. Running `awk' without Input Files
  720. ---------------------------------
  721.    You can also run `awk' without any input files.  If you type the
  722. command line:
  723.      awk 'PROGRAM'
  724. then `awk' applies the PROGRAM to the "standard input", which usually
  725. means whatever you type on the terminal.  This continues until you
  726. indicate end-of-file by typing `Control-d'.
  727.    For example, if you execute this command:
  728.      awk '/th/'
  729. whatever you type next is taken as data for that `awk' program.  If you
  730. go on to type the following data:
  731.      Kathy
  732.      Ben
  733.      Tom
  734.      Beth
  735.      Seth
  736.      Karen
  737.      Thomas
  738.      `Control-d'
  739. then `awk' prints this output:
  740.      Kathy
  741.      Beth
  742.      Seth
  743. as matching the pattern `th'.  Notice that it did not recognize
  744. `Thomas' as matching the pattern.  The `awk' language is "case
  745. sensitive", and matches patterns exactly.  (However, you can override
  746. this with the variable `IGNORECASE'. *Note Case-sensitivity in
  747. Matching: Case-sensitivity.)
  748. File: gawk.info,  Node: Long,  Next: Executable Scripts,  Prev: Read Terminal,  Up: Running gawk
  749. Running Long Programs
  750. ---------------------
  751.    Sometimes your `awk' programs can be very long.  In this case it is
  752. more convenient to put the program into a separate file.  To tell `awk'
  753. to use that file for its program, you type:
  754.      awk -f SOURCE-FILE INPUT-FILE1 INPUT-FILE2 ...
  755.    The `-f' instructs the `awk' utility to get the `awk' program from
  756. the file SOURCE-FILE.  Any file name can be used for SOURCE-FILE.  For
  757. example, you could put the program:
  758.      /th/
  759. into the file `th-prog'.  Then this command:
  760.      awk -f th-prog
  761. does the same thing as this one:
  762.      awk '/th/'
  763. which was explained earlier (*note Running `awk' without Input Files:
  764. Read Terminal.). Note that you don't usually need single quotes around
  765. the file name that you specify with `-f', because most file names don't
  766. contain any of the shell's special characters.  Notice that in
  767. `th-prog', the `awk' program did not have single quotes around it.  The
  768. quotes are only needed for programs that are provided on the `awk'
  769. command line.
  770.    If you want to identify your `awk' program files clearly as such,
  771. you can add the extension `.awk' to the file name.  This doesn't affect
  772. the execution of the `awk' program, but it does make "housekeeping"
  773. easier.
  774. File: gawk.info,  Node: Executable Scripts,  Prev: Long,  Up: Running gawk
  775. Executable `awk' Programs
  776. -------------------------
  777.    Once you have learned `awk', you may want to write self-contained
  778. `awk' scripts, using the `#!' script mechanism.  You can do this on
  779. many Unix systems (1) (and someday on GNU).
  780.    For example, you could create a text file named `hello', containing
  781. the following (where `BEGIN' is a feature we have not yet discussed):
  782.      #! /bin/awk -f
  783.      
  784.      # a sample awk program
  785.      BEGIN    { print "hello, world" }
  786. After making this file executable (with the `chmod' command), you can
  787. simply type:
  788.      hello
  789. at the shell, and the system will arrange to run `awk' (2) as if you
  790. had typed:
  791.      awk -f hello
  792. Self-contained `awk' scripts are useful when you want to write a
  793. program which users can invoke without knowing that the program is
  794. written in `awk'.
  795.    If your system does not support the `#!' mechanism, you can get a
  796. similar effect using a regular shell script.  It would look something
  797. like this:
  798.      : The colon makes sure this script is executed by the Bourne shell.
  799.      awk 'PROGRAM' "$@"
  800.    Using this technique, it is *vital* to enclose the PROGRAM in single
  801. quotes to protect it from interpretation by the shell.  If you omit the
  802. quotes, only a shell wizard can predict the results.
  803.    The `"$@"' causes the shell to forward all the command line
  804. arguments to the `awk' program, without interpretation.  The first
  805. line, which starts with a colon, is used so that this shell script will
  806. work even if invoked by a user who uses the C shell.
  807.    ---------- Footnotes ----------
  808.    (1)  The `#!' mechanism works on Unix systems derived from Berkeley
  809. Unix, System V Release 4, and some System V Release 3 systems.
  810.    (2)  The line beginning with `#!' lists the full pathname of an
  811. interpreter to be run, and an optional initial command line argument to
  812. pass to that interpreter.  The operating system then runs the
  813. interpreter with the given argument and the full argument list of the
  814. executed program.  The first argument in the list is the full pathname
  815. of the `awk' program.  The rest of the argument list will either be
  816. options to `awk', or data files, or both.
  817. File: gawk.info,  Node: Comments,  Next: Statements/Lines,  Prev: Running gawk,  Up: Getting Started
  818. Comments in `awk' Programs
  819. ==========================
  820.    A "comment" is some text that is included in a program for the sake
  821. of human readers, and that is not really part of the program.  Comments
  822. can explain what the program does, and how it works.  Nearly all
  823. programming languages have provisions for comments, because programs are
  824. typically hard to understand without their extra help.
  825.    In the `awk' language, a comment starts with the sharp sign
  826. character, `#', and continues to the end of the line.  The `awk'
  827. language ignores the rest of a line following a sharp sign. For
  828. example, we could have put the following into `th-prog':
  829.      # This program finds records containing the pattern `th'.  This is how
  830.      # you continue comments on additional lines.
  831.      /th/
  832.    You can put comment lines into keyboard-composed throw-away `awk'
  833. programs also, but this usually isn't very useful; the purpose of a
  834. comment is to help you or another person understand the program at a
  835. later time.
  836.